from tkinter import *
from tkinter.ttk import *
from typing import List


class MsGrid:
    # 绘制幻方表格类
    def __init__(self, master, n: int, magic_square: List[List[int]], sx: int, sy: int):
        self.n = n
        self.sx = sx
        self.sy = sy
        self.magic_square = magic_square
        self.labels = [[Label(master) for _ in range(n)] for _ in range(n)]

    @staticmethod
    def _click(event: Event):
        widget = event.widget
        if widget.cget("background").string == "white":
            event.widget.config(background="blue")
        else:
            event.widget.config(background="white")

    def labels_place(self):
        margin = len(str(self.n ** 2))
        for y in range(self.n):
            for x in range(self.n):
                label = self.labels[y][x]
                label.config(background="white",
                             text=self.magic_square[y][x],
                             font=("Arial", 20),
                             anchor=E,
                             width=margin)
                label.place(x=self.sx + x * margin * 19,
                            y=self.sy + y * 40)
                label.bind("<Button-1>", self._click)


class MsText:
    # 绘制幻方文本区域
    def __init__(self, master, sx: int, sy: int):
        self.sx, self.sy = sx, sy
        print(master.cget("width"))
        self.text = Text(master, wrap=NONE, width=70, height=30)  # wrap 跟随文字增加而增大（不换行）
        self.xscrollbar = Scrollbar(master, orient=HORIZONTAL)  # 水平方向滚动条
        self.yscrollbar = Scrollbar(master)
        self.text.config(yscrollcommand=self.yscrollbar.set,
                         xscrollcommand=self.xscrollbar.set)
        self.xscrollbar.config(command=self.text.xview)
        self.yscrollbar.config(command=self.text.yview)

    def text_place(self):
        """放置滚动条
        注意：放置代码是有顺序的，依次放置，避免外观出现问题
        """
        self.xscrollbar.pack(side=BOTTOM, fill=X)
        self.yscrollbar.pack(side=RIGHT, fill=Y)
        self.text.pack(fill=BOTH, padx=self.sx, pady=self.sy)

